package blog.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;
/**
 * MD5加密
 * */
public class Crypto {
	private static final Logger log = Logger.getLogger(Crypto.class);

	private static String MD5 = "MD5";

	public static String GetMessageDigest(String strSrc, String encName) {
		MessageDigest md = null;
		String strDes = null;
		final String ALGO_DEFAULT = "MD5";
		byte[] bt = strSrc.getBytes();
		try {
			if (isEmpty(encName)) {
				encName = ALGO_DEFAULT;
			}
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			strDes = bytes2Hex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
		log.debug(strDes);
		return strDes;
	}

	public static String GetMessageDigest(String strSrc) {
		return GetMessageDigest(strSrc, MD5);
	}

	private static boolean isEmpty(String str) {
		if (str == null || str.trim().equals("")) {
			return true;
		}
		return false;
	}

	/**
	 * 将字节数组转为HEX字符串(16进制串)
	 * 
	 * @param bts
	 *  要转换的字节数组
	 * @return 转换后的HEX串
	 */
	public static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}
}
